package com.seo.controller.keyWord;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRichTextString;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.github.pagehelper.PageInfo;
import com.seo.function.PageTool;
import com.seo.pojo.InputBody;
import com.seo.pojo.ReturnBody;
import com.seo.service.keyword.sdk.KeywordGService;
import com.seo.service.keyword.sdk.KeywordService;
import com.seo.service.sysUser.sdk.SysUserService;
import com.seo.utils.ClientConst;
import com.seo.utils.DateUtil;
import com.seo.utils.Jurisdiction;

import lombok.extern.slf4j.Slf4j;

/**
 * @ClassName: KeyWordController
 * @author rtc
 * @version 2018.07.28 12:20
 */
@Slf4j
@Controller
@RequestMapping(value = "/keyWord/")
public class KeyWordController {

	@Resource(name = "keywordService")
	private KeywordService keywordService;
	
	@Autowired
	private KeywordGService keywordGService;
	
	@Autowired
	private SysUserService sysUserService;
	
	@Autowired
	private PageTool pageTool;
	
	
	@RequestMapping(value = "/test", method = { RequestMethod.POST, RequestMethod.GET })
	@ResponseBody
	public String test(String param) throws Exception {
		return param;
	}

	/**
	 * 获取关键词报价
	 * 
	 * @param keyWord
	 *            关键词
	 * @param type
	 *            用户类型
	 * @return Map<String,Object>
	 */
	@RequestMapping(value = "/offer")
	public ModelAndView listOffer(@RequestParam Map<String, Object> param) throws Exception {
		log.info("获取关键词报价开始---param={}", param);
		ModelAndView mv = new ModelAndView();
		List<Map<String, Object>> keyWordOffer = null;
		if (!param.isEmpty()) {
			param.put("type", "00");
			param.put("userId", "0");
			keyWordOffer = keywordService.getKeyWordOffer(param);
		}
		mv.addObject("keyWord", param.get("keyWord"));
		mv.addObject("keyWordOffer", keyWordOffer);
		mv.setViewName("keyWord/keyWord_offer");
		log.info("获取关键词报价结束");
		return mv;
	}

	/**
	 * 跳转关键词新增
	 * 
	 * @param param
	 *            param
	 * @return ModelAndView
	 * @author rtc
	 * @version 2018.07.28 12:20
	 */
	@RequestMapping(value = "/toKeyWordAdd")
	public ModelAndView toKeyWordAdd() throws Exception {
		log.info("【跳转关键词新增】---【开始】---");
		ModelAndView mv = new ModelAndView();
		List<Map<String, Object>> engine = keywordService.getEngineList();
		mv.addObject("engine", engine);
		mv.setViewName("keyWord/keyWord_add");
		log.info("【跳转关键词新增】---【结束】---");
		return mv;
	}

	/**
	 * 关键词新增
	 * 
	 * @param param
	 *            param
	 * @return String
	 * @author rtc
	 * @version 2018.07.28 12:20
	 */
	@RequestMapping(value = "/add")
	@ResponseBody
	public ReturnBody add(@RequestParam Map<String, Object> param) throws Exception {
		log.info("【关键词新增】---【开始】---");
		ReturnBody rb = ReturnBody.init();
		Map<String, Object> user = Jurisdiction.getUser(ClientConst.SESSION_USER);
		try {
			if (param == null || param.isEmpty() || user == null || user.isEmpty()) {
				return rb.error("参数不能为空");
			}
			if (!param.containsKey("uploadType")) {
				return rb.error("请选择上传方式");
			}
			String uploadType = (String) param.get("uploadType");
			param.put("createId", user.get("id"));
			rb.run(keywordService.saveKeyWord(param, "01", uploadType));
			log.info("【关键词新增】---【结束】---");
			return rb;
		} catch (Exception e) {
			log.error("添加关键词异常[{}]", e);
			return rb.error();
		}

	}
	
	/**
	 * 跳转关键词新增信息
	 * 
	 * @return ModelAndView
	 * @author rtc
	 * @version 2018.07.28 12:20
	 */
	@RequestMapping(value = "/toMessage")
	public String toMessage(@RequestParam Map<String, Object> params, HttpServletRequest request) throws Exception {
		request.setAttribute("param", params);
		return "keyWord/keyWord_add_message";
	}

	/**
	 * 关键词指数列表
	 * 
	 * @return ModelAndView
	 * @author rtc
	 * @version 2018.07.28 12:20
	 */
	@RequestMapping(value = "/indexList")
	public ModelAndView indexList() throws Exception {
		log.info("【关键词指数列表】---【开始】---");
		ModelAndView mv = new ModelAndView();
		List<Map<String, Object>> indexList = keywordService.getKeyWordOffer();
		mv.addObject("indexList", indexList);
		mv.setViewName("keyWord/keyWord_index_list");
		log.info("【跳转关键词新增】---【结束】---");
		return mv;
	}

	/**
	 * 跳转新增关键词指数页面
	 * 
	 * @return ModelAndView
	 * @author rtc
	 * @version 2018.07.28 12:20
	 */
	@RequestMapping(value = "/toIndexAdd")
	public ModelAndView toIndexAdd() throws Exception {
		ModelAndView mv = new ModelAndView();
		mv.addObject("msg", "indexAdd");
		mv.setViewName("keyWord/keyWord_index_edit");
		return mv;
	}

	/**
	 * 跳转编辑关键词指数页面
	 * 
	 * @return ModelAndView
	 * @author rtc
	 * @version 2018.07.28 12:20
	 */
	@RequestMapping(value = "/toEditIndex")
	public ModelAndView toEditIndex(Integer id) throws Exception {
		ModelAndView mv = new ModelAndView();
		if (id == null) {
			mv.addObject("msg", "访问失败");
			mv.setViewName("keyWord/keyWord_index_list");
			return mv;
		}
		Map<String, Object> index = keywordService.getIndexById(id);
		mv.addObject("index", index);
		mv.addObject("msg", "updateIndex");
		mv.setViewName("keyWord/keyWord_index_edit");
		return mv;
	}

	/**
	 * 新增关键词指数
	 * 
	 * @return String
	 * @author rtc
	 * @version 2018.07.28 12:20
	 */
	@RequestMapping(value = "/indexAdd")
	public String indexAdd(HttpServletRequest request) throws Exception {
		log.info("保存指数");
		InputBody body = InputBody.init();
		ReturnBody rb = ReturnBody.init();
		String min_index = body.get("min_index", String.class);
		if (StringUtils.isEmpty(min_index)) {
			request.setAttribute("result", rb.error("最小指数不能为空").getResult());
			return "save_result";
		}
		String max_index = body.get("max_index", String.class);
		if (StringUtils.isEmpty(max_index)) {
			request.setAttribute("result", rb.error("最大指数不能为空").getResult());
			return "save_result";
		}
		String price_1 = body.get("price_1", String.class);
		if (StringUtils.isEmpty(price_1)) {
			request.setAttribute("result", rb.error("特殊词价格不能为空").getResult());
			return "save_result";
		}
		String price_2 = body.get("price_2", String.class);
		if (StringUtils.isEmpty(price_2)) {
			request.setAttribute("result", rb.error("正常词价格不能为空").getResult());
			return "save_result";
		}
		rb = keywordService.saveIndex(body.getParams());
		request.setAttribute("result", rb.success().getResult());
		return "save_result";
	}

	/**
	 * 修改关键词指数
	 * 
	 * @return String
	 * @author rtc
	 * @version 2018.07.28 12:20
	 */
	@RequestMapping(value = "/updateIndex")
	public String updateIndex(HttpServletRequest request) throws Exception {
		log.info("修改指数");
		InputBody body = InputBody.init();
		ReturnBody rb = ReturnBody.init();
		String id = body.get("id", String.class);
		if (StringUtils.isEmpty(id)) {
			request.setAttribute("result", rb.error("参数有误").getResult());
			return "save_result";
		}
		String min_index = body.get("min_index", String.class);
		if (StringUtils.isEmpty(min_index)) {
			request.setAttribute("result", rb.error("最小指数不能为空").getResult());
			return "save_result";
		}
		String max_index = body.get("max_index", String.class);
		if (StringUtils.isEmpty(max_index)) {
			request.setAttribute("result", rb.error("最大指数不能为空").getResult());
			return "save_result";
		}
		String price_1 = body.get("price_1", String.class);
		if (StringUtils.isEmpty(price_1)) {
			request.setAttribute("result", rb.error("特殊词价格不能为空").getResult());
			return "save_result";
		}
		String price_2 = body.get("price_2", String.class);
		if (StringUtils.isEmpty(price_2)) {
			request.setAttribute("result", rb.error("正常词价格不能为空").getResult());
			return "save_result";
		}
		rb = keywordService.updateIndex(body.getParams());
		request.setAttribute("result", rb.success().getResult());
		return "save_result";
	}

	@RequestMapping("/deleteIndex")
	@ResponseBody
	public String deleteIndex(Integer id) {
		log.info("删除指数...");
		if (id == null || id <= 0) {
			return "error";
		}
		int num = keywordService.deleteIndex(id);
		return num == 0 ? "error" : "success";
	}
	
	/**
	 * 回收站
	 * @param param 关键词
	 * @return Map<String,Object>
	 */
	@RequestMapping(value = "/recycleBin")
	public ModelAndView recycleBin(@RequestParam Map<String, Object> param, HttpServletRequest request) throws Exception {
		log.info("【获取回收站数据】---【开始】--param={}", param);
		ModelAndView mv = new ModelAndView();
		List<Map<String, Object>> venderList = keywordGService.getVenderList(); //厂商列表
		List<Map<String, Object>> engineList = keywordGService.getEngineList(); //搜索引擎列表
		Integer id = Jurisdiction.getT("id", Integer.class, ClientConst.SESSION_USER);
		Map<String, Object> sysUser = sysUserService.getSysUserById(id);
		String dataAuthority = (String)sysUser.get("dataAuthority");
		Map<String, Object> p2 = new HashMap<>();
		if("00".equals(dataAuthority)) {
			param.put("belongId", id);
			p2.put("belongId", id);
		}
		p2.put("startTime", DateUtil.getTimesmorning());
		p2.put("endTime", DateUtil.getAfterDayDate(DateUtil.getTimesmorning(), 1, 1));
		PageInfo<?> page = pageTool.getAutoPage(keywordService::getRecycleBinList, param);
		int todayNum = keywordService.getRecycleBinCnt(p2);
		request.setAttribute("page", page);
		request.setAttribute("todayNum", todayNum);
		request.setAttribute("venderList", venderList);
		request.setAttribute("engineList", engineList);
		mv.setViewName("keyWord/keyWord_recycleBin");
		log.info("【获取回收站数据】---【结束】---");
		return mv;
	}
	
	/**
	 * 导出回收站列表
	 * @param pam
	 * @param response
	 */
	@RequestMapping("exportRecycleBin")
	public void exportKeyWord(@RequestParam Map<String, Object> pam, HttpServletResponse response){
		XSSFWorkbook workbook = new XSSFWorkbook();
		try {
			XSSFSheet sheet = workbook.createSheet("信息表");
			List<Map<String, Object>> export = keywordService.getRecycleBinList(pam); // 导出数据
			String fileName = "回收站列表-" + DateUtil.getDay() + ".xlsx";// 设置要导出的文件的名字
			// 新增数据行，并且设置单元格数据

			int rowNum = 1;
			String[] headers = { "ID", "用户名", "关键词", "域名", "引擎", "指数","单价 (元)","厂商","修改时间" };
			// headers表示excel表中第一行的表头

			XSSFRow row = sheet.createRow(0);
			// 在excel表中添加表头

			for (int i = 0; i < headers.length; i++) {
				XSSFCell cell = row.createCell(i);
				XSSFRichTextString text = new XSSFRichTextString(headers[i]);
				cell.setCellValue(text);
			}
			Map<String, Object> exportMap = null;
			// 在表中存放查询到的数据放入对应的列
			for (int i = 0; i < export.size(); i++) {
				XSSFRow row1 = sheet.createRow(rowNum);
				exportMap = export.get(i);
				String engineCode = (String) exportMap.get("engine_code");
				if("01".equals(engineCode)) {
					engineCode= "百度PC";
				} else if("02".equals(engineCode)) {
					engineCode= "百度移动";
				} else if("03".equals(engineCode)) {
					engineCode= "360PC";
				} else if("04".equals(engineCode)) {
					engineCode= "360移动";
				} else if("05".equals(engineCode)) {
					engineCode= "神马";
				} else if("06".equals(engineCode)) {
					engineCode= "搜狗pc";
				} else if("07".equals(engineCode)) {
					engineCode= "搜狗移动";
				}
				Long keyword_index = (Long) exportMap.get("keyword_index");
				
				if(keyword_index == -1L) {
					keyword_index = 0L;
				}
			
				row1.createCell(0).setCellValue(exportMap.get("id").toString());
				row1.createCell(1).setCellValue(exportMap.get("userName").toString());
				row1.createCell(2).setCellValue(exportMap.get("name").toString());
				row1.createCell(3).setCellValue(exportMap.get("domain").toString());
				row1.createCell(4).setCellValue(engineCode);
				row1.createCell(5).setCellValue(keyword_index);
				row1.createCell(6).setCellValue(exportMap.get("price").toString());
				row1.createCell(7).setCellValue(String.valueOf(exportMap.get("venderName")));
				row1.createCell(8).setCellValue(exportMap.get("update_time").toString());
				rowNum++;
			}
			response.setContentType("application/octet-stream");
			response.setHeader("Content-disposition",
					"attachment;filename=" + new String(fileName.getBytes("utf-8"), "ISO-8859-1"));
			response.flushBuffer();
			workbook.write(response.getOutputStream());
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	
	@RequestMapping("/keyWordUpdate")
	@ResponseBody
	public String keyWordUpdate(@RequestParam Map<String, Object> pam) {
		log.info("进入恢复关键词方法...");
		String msg = "";
		try {
			keywordService.keyWordUpdate(pam);
			msg = "true";
		} catch (Exception e) {
			msg = "error";
		}
		
		return msg;
	}
	
	@RequestMapping("/deleteK")
	@ResponseBody
	public String deleteK(@RequestParam Map<String, Object> pam) {
		log.info("进入删除关键词方法...");
		String msg = "";
		try {
			keywordService.deleteK(pam);
			msg = "true";
		} catch (Exception e) {
			msg = "error";
		}
		
		return msg;
	}
	
}
